package com.ss.web.tagmark.dao;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.persistence.EntityManager;

import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;

import com.ss.web.tagmark.entity.TagExtend;
import com.ss.web.tagmark.entity.TagInfo;
import com.ss.web.tagmark.entity.User;

public interface TagDao extends BaseRepository<TagInfo, Long> {

	default Page<TagInfo> findByPage(TagInfo tag, Pageable page, EntityManager em) {
		String sql = "SELECT * FROM  `tag_info` t WHERE 1=1 ";
		Map<String, Object> params = new HashMap<>();
		if (StringUtils.isNotBlank(tag.getName())) {
			sql += " and (MATCH(`name`) AGAINST (CONCAT('*',:name,'*') IN BOOLEAN MODE) OR name_py like concat(:name,'%') OR name_py_short like concat(:name,'%'))";
			params.put("name", tag.getName());
		}
		if (tag instanceof TagExtend) {
			TagExtend t = (TagExtend) tag;
			if (t.getUsers() != null && t.getUsers().size() > 0) {
				List<Long> userIds = new ArrayList<>();
				sql += " AND t.`tag_id` IN (SELECT ut.tag_id FROM user_tag ut where ut.user_id in (:userId))";
				for (User user : t.getUsers()) {
					if (user == null || user.getUserId() == null) {
						continue;
					}
					userIds.add(user.getUserId());
				}
				params.put("userId", userIds);
			}
		}
		return doQuery(page, sql, TagInfo.class, params, em);
	}

	@Query(nativeQuery = true, value = "select * from tag_info WHERE MATCH(`name`) AGAINST( concat('*',:q,'*') IN BOOLEAN MODE) OR name_py like concat(:q,'%') OR name_py_short like concat(:q,'%')  limit 20")
	public List<TagInfo> find4Search(@Param("q") String q);

	@Query(nativeQuery = true, value = "SELECT t.* FROM tag_info t INNER JOIN user_tag ut ON t.`tag_id`=ut.`tag_id` WHERE ut.`user_id`=:userId limit 100")
	public List<TagInfo> findByUserId(@Param("userId") Long userId);

	public TagInfo findByName(String tagName);

}
